/**
 * Copyright (c) 2011 Nokia Corporation.
 *
 */

#include <QMatrix4x4>
#include <QDebug>
#include <math.h>
#include <memory.h>
#include <assert.h>
#include "QPainterSpriteBatch.h"


QPainterSpriteBatch::QPainterSpriteBatch(int w, int h, QPaintDevice *paintDevice, QObject *parent  ) :
    QObject(parent), SpriteBatch(w,h), device(paintDevice), painter(0)
{
    assert(device);
}

QPainterSpriteBatch::~QPainterSpriteBatch()
{
    end();
}

void QPainterSpriteBatch::begin(BlendMode bmode, TransformMode dTransform, float *cpm )
{
    // TODO custom projection
    assert(!painter);

    painter = new QPainter(device);
    painter->setRenderHint(QPainter::SmoothPixmapTransform);

    switch(bmode)
    {
    case SpriteBatch::eADDITIVE:
        painter->setCompositionMode(QPainter::CompositionMode_Plus);
        break;
    default:
        painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
        break;
    }
}

void QPainterSpriteBatch::end()
{
    if(!painter) return;
    painter->end();
    delete painter;
    painter=NULL;
}

void QPainterSpriteBatch::draw( SpriteDrawInfo *sdi, int count )
{
    // TODO isnt there any fast way to make rgb tint?
    // TODO custom projection

    assert(painter);

    for(int i=0;i<count;i++)
    {
        painter->resetTransform();

        QPixmap *pixmap=(QPixmap *)sdi->textureHandle;

        QRectF target(0, 0, sdi->scaleX, sdi->scaleY);
        QRectF source(sdi->sourcex*pixmap->width(), sdi->sourcey*pixmap->height(), sdi->sourceWidth*pixmap->width(), sdi->sourceHeight*pixmap->height());

        painter->translate(sdi->posx, targetHeight-sdi->posy);
        painter->rotate(sdi->angle*360/(M_PI*2));
        painter->translate(-sdi->originX*sdi->scaleX, -sdi->originY*sdi->scaleY);

        painter->setOpacity(sdi->a);
        painter->drawPixmap(target, *pixmap, source);

        sdi++;
    }
}

